<template>
  <div class="supplier-add-container ">
    <div class="items-box">
      <div class="items">
        <label>
          <span class="require-star">*</span>商品名
        </label>
        <input
          type="text"
          class="input"
          name="title"
          placeholder="请输入商品名"
          v-model="formData.title"
        />
      </div>
      <div class="items">
        <label>
          <span class="require-star">*</span>供货价
        </label>
        <input
          type="number"
          class="input"
          name="cost_price"
          placeholder="请输入供货价格"
          v-model="formData.cost_price"
        />
        <span class="unit">元</span>
      </div>
    </div>
    <div class="items-box">
      <div class="items">
        <label>
          <span class="require-star">*</span>原价
        </label>
        <input
          type="number"
          class="input"
          name="original_price"
          placeholder="请输入商品原价"
          v-model="formData.original_price"
        />
        <span class="unit">元</span>
      </div>
      <div class="items">
        <label>
          <span class="require-star">*</span>现价
        </label>
        <input
          type="number"
          class="input"
          name="price"
          placeholder="请输入商品现价"
          v-model="formData.price"
        />
        <span class="unit">元</span>
      </div>
    </div>
    <div class="items-box">
      <div class="items">
        <label>
          <span class="require-star">*</span>库存
        </label>
        <input type="number" class="input" name="num" placeholder="请输入商品库存" v-model="formData.num" />
      </div>
      <div class="items">
        <label class="fl">
          <span class="require-star">*</span>运费
        </label>
        <div class="freight-radio-group fl">
          <van-radio-group v-model="formData.post_fee_radio" icon-size="16" color="#CCCCCC" checked-color="#F20B22" direction="horizontal" @change="changePostRadio">
            <div class="freight-radio-box">
              <van-radio class="freight-radio" name="1">包邮</van-radio>
              <van-radio class="freight-radio" name="4">到付</van-radio>
            </div>
            <div class="freight-radio-box">
              <van-radio class="freight-radio" name="2">统一运费</van-radio>
              <!-- <span> -->
                <input type="number" class="input xmini j-feight-ipt" name="post_fee" v-model="formData.post_fee" :disabled="postFeeDisabled"/>
                <span>元</span>
              <!-- </span> -->
            </div>

            <div class="freight-radio-box">
              <van-radio class="freight-radio" name="3">运费模板</van-radio>
              <select
                name="freight_tpl_id"
                class="freight_select"
                id="freight_tpl_id"
                :disabled="freightSelectDisabled"
                v-model="formData.freight_tpl_id"
              >
                <option value="-1">请选择</option>
                <option
                  v-for="(value,index) in freight_tpl_list"
                  :key="index"
                  :value="value.freight_tpl_id"
                >{{value.title}}</option>
                <!-- :selected="value.freight_tpl_id==item_info.freight_tpl_id?'true':'false'" -->
              </select>
            </div>
          </van-radio-group>
        </div>
        <!-- <input type="number" class="input" name="post_fee" placeholder="请输入运费" value="{$item_info.post_fee}"/> -->
      </div>
    </div>
    <div class="items-box">
      <div class="items item-flex">
        <label>重量</label>
        <input
          type="number"
          class="input"
          name="weight"
          placeholder="请输入数字"
          v-model="formData.weight"
        />
        <span class="unit">千克(最多四位小数)</span>
      </div>
      <div class="items item-flex">
        <label>体积</label>
        <input
          type="number"
          class="input"
          name="volume"
          placeholder="请输入数字"
          v-model="formData.volume"
        />
        <span class="unit">m³(最多四位小数)</span>
      </div>
    </div>
    <div class="items-box">
      <div class="items classification" v-if="classificationList.length>0">
        <label>商品分类</label>
        <span class="unit" @click="productClassification('classification')">{{formData.class_id.length > 0 ? '重新选择' : '点击选择'}}</span>
      </div>
      <div class="items classification" v-if="groupList.length>0">
        <label>商品分组</label>
        <span class="unit" @click="productClassification('group')">{{formData.group_id.length > 0 ? '重新选择' : '点击选择'}}</span>
      </div>
    </div>
    <div class="items-box">
      <div class="items">
        <label class="long-label">商家编码</label>
        <input
          type="number"
          class="input"
          name="goods_no"
          placeholder="请输入商家编码"
          v-model="formData.goods_no"
        />
      </div>
      <div class="items items_img">
        <label class="fl long-label">
          <span class="require-star">*</span>商品图片
        </label>
        <div class="img-box fl">
          <!-- TODO 上传商品图片 -->
          <SmallUploadImg ref="smallUploadImg" :imageList="imgArr" :maxLength="5"></SmallUploadImg>
          <p class="watch"><span class="require-star">*</span>最多上传5张图片</p>
        </div>
        <!-- <input type="hidden" name="imglistdata" class="j-imglist-dataset" value="{$img}" /> -->
      </div>
    </div>
    <div class="items-box" v-show="!itemId">
      <div class="items good_intro">
        <label class="long-label">商品简介</label>
        <div class="text_box">
          <textarea class="editcontent" id="edit_content" v-model="formData.content"></textarea>
        </div>
      </div>
      <div class="items items_img">
        <label class="fl long-label">详情图片</label>
        <div class="img-box fl">
          <!-- TODO 上传商品图片 -->
          <SmallUploadImg ref="smallUploadImgList" :imageList="imgList" :maxLength="10"></SmallUploadImg>
          <p class="watch"><span class="require-star">*</span>最多上传10张图片</p>
        </div>
        <!-- <input type="hidden" name="imglistdata" class="j-imglist-dataset" value="{$img}" /> -->
      </div>
      <div class="tip">注：更多信息请到PC端添加</div>
      <div class="tip" style="color: #FE1B49;">注：商品简介和商品详情图片仅可以在添加商品时进行操作</div>
    </div>
    <div class="btn-box">
      <div class="btn-submit drafts-btn" @click="clickDrafts">保存草稿</div>
      <div class="btn-submit" @click="clickSubmit">提交</div>
    </div>
    <van-popup
      v-model="classificationShow"
      round
      class="type-pop"
      position="bottom"
      :style="{ height: '70%' }"
    >
    <div class="type-wrap">
      <div class="type-title">{{contentType == 1 ? '商品分类' : '商品分组'}}<span @click="closePop"><img src="https://img.wifenxiao.com/h5-wfx/images/common/close-icon.png"></span></div>
      <div class="type-content">
        <van-checkbox-group v-model="showClick" >
          <div v-for="item in showList" :key="item.group_id || item.class_id">
            <div class="type-item" @click="classificationClick(item)">
              <div class="list-item" :class="item.show ? 'launch':''" v-if="contentType == 1"><img src="https://img.wifenxiao.com/h5-wfx/images/down-new.png" v-if="item._child && item._child.length>0"></div>
              <div><van-checkbox @click.stop="setId(item, 'one')" icon-size="16" :name="item.group_id || item.class_id" checked-color="#FF2A40">{{item.class_name || item.title}}</van-checkbox></div>
            </div>
            <template v-if="item._child && item._child.length>0 && item.show">
              <template v-for="two in item._child">

                <div class="type-item two-class"  :key="two.id">
                  <div class="list-item" :class="item.show ? 'launch':''"><img src="https://img.wifenxiao.com/h5-wfx/images/down-new.png" @click="classificationClick(two)" v-if="two._child && two._child.length>0"></div>
                  <div><van-checkbox @click.stop="setId(two, 'two', item)" icon-size="16" :name="two.group_id || two.class_id"  checked-color="#FF2A40">{{two.class_name || two.title}}</van-checkbox></div>
                </div>
                <template v-if="two._child && two._child.length>0 && two.show">
                  <div class="type-item three-class" v-for="three in two._child" :key="three.id">
                    <van-checkbox @click.stop="setId(three, 'three', item, two)" icon-size="16" :name="three.group_id || three.class_id" checked-color="#FF2A40">{{three.class_name || three.title}}</van-checkbox>
                  </div>
                </template>
              </template>
            </template>
         
          </div>
        </van-checkbox-group>
      </div>
      <div class="click-btn">
        <div class="type-close" @click="clickOk">确定</div>
      </div>
    </div>
    </van-popup>
  </div>
</template>

<script>
import { validLength } from '@/utils/validate.js'
import { getSupplierAddItem, supplierAddItemDo } from '@/api/user/gys/gysApi'
import UploadImg from '@/components/UploadImg'
import SmallUploadImg from '@/components/SmallUploadImg'
import Vue from 'vue'
import { RadioGroup, Radio, Checkbox, CheckboxGroup } from 'vant'
Vue.use(Checkbox)
Vue.use(CheckboxGroup)
Vue.use(Radio)
Vue.use(RadioGroup)
export default Vue.extend({
  name: 'index',
  components: {
    UploadImg,
    SmallUploadImg
  },
  data() {
    return {
      imgArr: [],
      imgList: [],
      itemId: '',
      draftsId: '', // 草稿箱 id
      freight_tpl_list: '',
      img: '',
      item_info: '',
      postFeeDisabled: true,
      freightSelectDisabled: true,
      formData: {
        title: '',
        cost_price: '', // 供货价
        original_price: '',
        price: '',
        num: '',
        // freight_payer: '', // 运费方式
        post_fee_radio: '1',
        post_fee: '',
        freight_tpl_id: '-1',
        weight: '',
        volume: '',
        goods_no: '',
        content: '',
        imglistdata: [],
        imglist: [],
        group_id: [], // 分类选中
        class_id: [], // 分组选中
      },
      showList: {}, // 展示分类/分组的数据
      showClick: [], // 展示的分类/分组选中数据
      contentType: '', // 展示分类/分组弹窗的标题 1:商品分类 2：商品分组
      classificationShow: false, // 弹出层是否展示
      classificationList: [], // 分类的数据
      groupList: [] // 分组的数据
    }
  },
  methods: {
    init(id) {
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 50000)
      let params = {}
      if (id) {
        params.id = id
        this.formData.id = id
        // TODO title处理
        wx.setNavigationBarTitle({
          title: '编辑商品'
        })
        if (this.draftsId) {
          this.formData.drafts_id = this.draftsId
          params.drafts_id = this.draftsId
        }
      }
      getSupplierAddItem(params).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          const resData = res.data
          if (resData.item_info) {
            this.item_info = resData.item_info
            this.formData.title = this.item_info.title
            this.formData.cost_price = this.item_info.cost_price
            this.formData.original_price = this.item_info.original_price
            this.formData.price = this.item_info.price
            this.formData.num = this.item_info.num
            this.formData.post_fee_radio = this.item_info.freight_payer
            if (this.formData.post_fee_radio == 2) {
              this.postFeeDisabled = false
            } else {
              this.postFeeDisabled = true
            }
            if (this.formData.post_fee_radio == 3) {
              this.freightSelectDisabled = false
            } else {
              this.freightSelectDisabled = true
            }
            this.formData.post_fee = this.item_info.post_fee
            this.formData.freight_tpl_id = this.item_info.freight_tpl_id || '-1'
            this.formData.weight = this.item_info.weight
            this.formData.volume = this.item_info.volume
            this.formData.goods_no = this.item_info.goods_no
          }
          this.formData.drafts_id = resData.drafts_id
          this.formData.content = resData.content ? (resData.content).replaceAll('<p>', '').replaceAll('</p>', '') : ''
          this.freight_tpl_list = resData.freight_tpl_list
          this.classificationList = resData.class_lists
          this.formData.class_id = resData.selected_class_ids
          this.formData.group_id = resData.selected_group_ids
          this.groupList = resData.group
          if (resData.img && resData.img.length > 0) {
            const imgArr = resData.img.split(',')
            // TODO 图片处理
              this.imgArr = imgArr
            
          }
          if (resData.imglist && resData.imglist.length > 0) {
            const img = resData.imglist.split(',')
            // TODO 图片处理
              this.imgList = img
            
          }
        } else {
          this.$Error(res.msg)
        }
      })
    },
    // uploadImg 抛出的图片参数
    uploadImgListIssue(val) {
      const arr = []
      val.forEach(item => {
        if (item.url) {
          arr.push(item.url)
        } else {
          arr.push(item.content)
        }
      })
      this.formData.imglistdata = arr
    },
    // 修改运费方式
    changePostRadio() {
      if (this.formData.post_fee_radio == 2) {
        this.postFeeDisabled = false
      } else {
        this.postFeeDisabled = true
      }
      if (this.formData.post_fee_radio == 3) {
        this.freightSelectDisabled = false
      } else {
        this.freightSelectDisabled = true
      }
    },
    // 草稿
    clickDrafts () {
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 10000)
      supplierAddItemDo({
          save_type: 'save_drafts',
          ...this.formData
        }).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          this.$Error('已保存到我的草稿箱')
          setTimeout(() => {
            this.$JumpPath(this, 'supplierDrafts')
          })
        } else {
          this.$Error(res.msg)
        }
      })
    },
    // 点击保存
    clickSubmit() {
      if (!validLength(this.formData.title)) {
        this.$Error('商品名称不能为空')
        return false
      }
      if (!validLength(this.formData.cost_price)) {
        this.$Error('供货价不能为空')
        return false
      }
      if (!validLength(this.formData.original_price)) {
        this.$Error('原价不能为空')
        return false
      }
      if (!validLength(this.formData.price)) {
        this.$Error('现价不能为空')
        return false
      }
      if (!validLength(this.formData.num)) {
        this.$Error('商品库存不能为空')
        return false
      }
      // 现价不能低于供货价
      if (this.formData.price - this.formData.cost_price < 0) {
        this.$Error('现价不能低于供货价')
        return false
      }
      // 统一运费筛选判断
      if (this.formData.post_fee_radio == 2) {
        if (this.formData.post_fee < 0) {
          this.$Error('运费不能小于0！')
          return false
        }
      } else if (this.formData.post_fee_radio == 3) {
      // 运费模版筛选判断
        if (this.formData.freight_tpl_id == -1) {
          this.$Error('请选择运费模版！')
          return false
        }
      }
      // TODO 图片数组处理
        if (this.$refs.smallUploadImg.imgList.length) {
          this.formData.imglistdata = this.$refs.smallUploadImg.imgList
        }
        if (this.$refs.smallUploadImgList.imgList.length) {
          this.formData.imglist = this.$refs.smallUploadImgList.imgList
        }
      if (this.formData.imglistdata.length <= 0) {
        this.$Error('商品图片不能为空')
        return false
      }
      // console.log(this.formData)
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 10000)
      supplierAddItemDo({
          save_type: 'save_item',
          ...this.formData
        }).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          this.$Error('提交成功')
          setTimeout(() => {
              // TODO 返回供应商商品列表
              wx.navigateBack({
                delta: 1
              })
              window.$$publish('refreshList', true)
          }, 1000)
        } else {
          this.$Error(res.msg)
        }
      })
    },
    productClassification(name) {
      if (name == 'classification') {
        this.showList = this.classificationList
        this.contentType = 1
        this.showClick = this.formData.class_id || []
      } else if (name == 'group') {
        this.showList = this.groupList
        this.contentType = 2
        this.showClick = this.formData.group_id || []
      }
      this.classificationShow = true

    },
    classificationClick(item) {
      if (item._child && item._child.length > 0) {
        item.show = !item.show
        this.showList = { ...this.showList }
      }
    },
    closePop() {
      this.classificationShow = false
      this.contentType = ''
      this.showList = []
    },
    setId(item, level, oneList, twoList) {
      // item.show = !item.show
      // this.showList = { ...this.showList }
      const newArr = []
      if (item._child && item._child.length > 0) {
        for (const i in item._child) {
          newArr.push(item._child[i].class_id || item._child[i].class_id.group_id)
          if (item._child[i]._child && item._child[i]._child.length > 0) {
            for (const k in item._child[i]._child) {
              newArr.push(item._child[i]._child[k].class_id || item._child[i]._child[k].group_id)
            }
          }
        }
      }
      // 选中
      if (this.showClick.includes(item.class_id)) {
        item.show = true
        if (item._child && item._child.length > 0) {
          for (const i in item._child) {
            if (item._child[i]._child && item._child[i]._child.length > 0) {
              item._child[i].show = true
            }
          }
        }
        this.showList = { ...this.showList }
        this.showClick.push(...newArr)
        if (level == 'two') {
          this.showClick.push(oneList.class_id || oneList.group_id)
        }
        if (level == 'three') {
          this.showClick.push(oneList.class_id || oneList.group_id)
          this.showClick.push(twoList.class_id || twoList.group_id)
        }
      } else {
        item.show = false
        this.showList = { ...this.showList }
        // 取消选中
        let twoNew = []
        if (level == 'two') {
        // if (oneList) {
          for (const i in oneList._child) {
            if (this.showClick.includes(oneList._child[i].class_id || oneList._child[i].class_id.group_id)) {
              twoNew.push(oneList._child[i].class_id || oneList._child[i].class_id.group_id)
            }
          }
        }
        if (level == 'three') {
        // if (twoList) {
          twoNew = []
          for (const i in twoList._child) {
            if (this.showClick.includes(twoList._child[i].class_id || twoList._child[i].class_id.group_id)) {
              twoNew.push(twoList._child[i].class_id || twoList._child[i].class_id.group_id)
            }
          }
        }
        const result = twoNew.every(value => !this.showClick.includes(value))
        if (result) {
          if (level == 'two') {
            newArr.push(oneList.class_id || oneList.group_id)
          }
          if (level == 'three') {
            // newArr.push(oneList.class_id || oneList.group_id)
            newArr.push(twoList.class_id || twoList.group_id)
            for (const i in oneList._child) {
              if (this.showClick.includes(oneList._child[i].class_id || oneList._child[i].class_id.group_id)) {
                twoNew.push(oneList._child[i].class_id || oneList._child[i].class_id.group_id)
              }
            }
            if (twoNew.length == 1 && (twoNew[0] == twoList.class_id || twoList.group_id)) {
              newArr.push(oneList.class_id || oneList.group_id)
            }
          }
        }
        const filteredArray = this.showClick.filter(item => !newArr.includes(item))
        this.showClick = filteredArray
      }
      this.showClick = [...new Set(this.showClick)]
    },
    clickOk() {
      if (this.contentType == 1) {
        this.formData.class_id = this.showClick
      } else if (this.contentType == 2) {
        this.formData.group_id = this.showClick
      }
      this.classificationShow = false
    }
  },
  created() {
    const query = this.$route.query
    this.itemId = query.itemId
    this.draftsId = query.draftsId
    this.init(this.itemId)
  }
})
</script>
<style lang="scss">
.supplier-add-container{
  .van-uploader__upload,.van-uploader__preview-image{
    width:160px;
    height:160px;
    border-radius: 8px;
    border:0;
    background:#fff;
  }
  .van-uploader__upload{
    background:#f4f4f4 url("https://img.wifenxiao.com/h5-wfx/images/upload_camera.png") center 50px no-repeat;
    background-size: 60px;
    .van-uploader__upload-icon{
      margin-top:20px;
      &::before{
        content:"";
        font-size: 20px;
        font-weight: normal;
      }
    }
  }
}
</style>
<style lang="scss">
@import "src/styles/variables";
@import "src/styles/mixin";
.supplier-add-container{
  .items-box{
    margin:20px 25px;
    border-radius:20px;
    background: #fff;
    padding: 0 28px;
    .require-star{
      color:#F30C23;
      margin-right: 6px;
    }
    .items{
      display: flex;
      align-items: center;
      font-size: 0;
      border-top:1px solid #ededed;
      overflow: hidden;
      &.item-flex {
        justify-content: space-between;
        input {
          width: 200px;
          position: relative;
          left: -28px;
        }
        .unit {
          width: 300px;
          text-align: right;
        }
      }
      &.good_intro{
        display: block;
      }
      &:first-child{
        border:0;
      }
      &.classification {
        justify-content: space-between;
      }
      label{
        font-weight: 400;
        line-height:96px;
      }
      >label{
        font-family: PingFang SC;
        display:inline-block;
        width:150px;
        font-size: 28px;
        &.long-label{
          width:150px;
        }
      }
      >input{
        font-family: PingFang SC;
        font-size: 28px;
        color: #999;
        display: inline-block;
        width: calc(100% - 200px);
        height: 95px;
        line-height: 95px;
        // padding: 20px 0;
        overflow: initial;
      }
      .unit{
        float:right;
        font-family: PingFang SC;
        font-size: 28px;
        line-height:96px;
      }
      .freight-radio-group{
        width: calc(100% - 150px);
        font-size: 28px;
        padding-bottom: 20px;
        .freight-radio-box{
          display: flex;
          align-items: center;
          .freight-radio{
            height: 96px;
            display: flex;
            margin-right: 20px;
          }
          input:disabled{
            background:#f7f7f7;
          }
          .xmini{
          padding:0 6px;
          }
          .xmini,select{
            font-size: 28px;
            width:280px;
            height:72px;
            padding: 20px 15px;
            border:2px solid #ededed;
            border-radius:4px;
          }
          span{
            flex: 1;
            line-height: 96px;
            text-align: right;
          }
        }
      }
      &.items_img{
        padding-top:20px;
      }
      .img-box{
        width:500px;
      }
      .watch{
        font-size:24px;
        color:#999;
        line-height:1.5;
        padding-bottom:30px;
      }
      .editcontent{
        width:100%;
        height:300px;
        padding:0 20px;
        border-radius:6px;
        border:1px solid #f0f0f0;
        background:#fafafa;
      }
      .text_box{
        height:200px;
        border: 1px solid #EDEDED;
        textarea{
          font-size: 24px;
          line-height: 28px;
          width: 100%;
          height: 100%;
          padding: 20px;
          resize:none;
          background: transparent;
        }
      }
      
    }
  }
  .btn-box{
    margin:30px 20px;
    .btn-submit{
      font-size:30px;
      color:#fff;
      height:92px;
      line-height:92px;
      text-align:center;
      border-radius:46px;
      @include gradient(right,#FE1B49,#E90104);
      &.drafts-btn {
        @include gradient(right,#ffaf39, #ffaf39);
        margin-bottom: 20px
      }
    }
  }
}
.tip{
  font-size:24px;
  color: #999;
  padding:20px 0 40px;
  margin-bottom: 20px;
}
.type-pop{
  padding: 0 20px 100px;
  .type-wrap{
    .type-title{
      font-size: 32px;
      text-align: center;
      // font-weight: bold;
      line-height: 110px;
      color: #333333;
      border-bottom: 1px solid #F0F0F0;
      position: fixed;
      width: 100%;
      z-index: 10;
      background: #fff;
      span {
        position: absolute;
        right: 50px;
        top: 6px;
        img {
          width: 32px
        }
      }
    }
    .type-content{
      overflow: auto;
      // height:400px;
      // margin: 40px 0;
      text-align: center;
      font-size: 32px;
      // margin-bottom: 80px;
      padding-top: 110px;
      .item{
        padding:24px 0;
      }
      .type-item {
        display: flex;
        font-size: 28px;
        border-bottom: 1px solid #F0F0F0;
        padding-bottom: 30px;
        margin: 30px;
        &.two-class {
          margin-left: 60px;
        }
        &.three-class {
          margin-left: 120px;
        }
        .list-item {
          display: block;
          width: 20px;
          margin-right: 20px;
          transition: rotate 1s;
          &.launch {
            transform: rotate(180deg);
          }
          img {
            width: 20px;
            position: relative;
            top: 10px;
          }
        }
      }
    }
    .click-btn {
      position: fixed;
      bottom: 0px;
      left: 0;
      right: 0;
      padding: 0 40px 40px 40px;
      background: #fff;
      .type-close{
        width: 100%;
        line-height: 76px;
        background: linear-gradient(270deg, #E90104 0%, #FE1B49 100%, #FE1B49 100%);
        border-radius: 38px;
        text-align: center;
        font-size: 28px;
        color: #fff;
      }
    }
    
  }
}
</style>
